from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common import alert
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class OpenAndLogin:
    def open_and_login(chrome_driver_path, url, username, password, role_value):
        # 创建一个 Chrome 浏览器的 WebDriver 实例
        service = ChromeService(executable_path=chrome_driver_path)
        driver = webdriver.Chrome(service=service)

        try:
            # 最大化浏览器窗口（可选）
            driver.maximize_window()

            # 打开目标网址
            driver.get(url)

            # 等待用户名输入框出现，并输入用户名
            username_field = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "input[placeholder='请输入账号']"))
            )
            username_field.clear()
            username_field.send_keys(username)
            time.sleep(1)  # 简单的延迟

            # 输入密码
            password_field = driver.find_element(By.CSS_SELECTOR, "input[placeholder='请输入密码']")
            password_field.clear()
            password_field.send_keys(password)
            time.sleep(1)

            # 选择角色
            # 等待角色选择框出现
            role_select=driver.find_elements(By.CLASS_NAME,"el-input__inner")
            role_select[2].click()
            time.sleep(1)
            role_select=driver.find_elements(By.CLASS_NAME, "el-select-dropdown__item")
            role_select[0].click()
            time.sleep(1)

            # 点击登录按钮
            login_button = driver.find_element(By.CSS_SELECTOR, "button[type='button']")
            login_button.click()
            time.sleep(5)  # 给予足够的时间以确认登录过程完成
            print("Login process completed.")

            # 关闭通知弹框
            close_button = driver.find_element(By.CLASS_NAME, "el-button")
            time.sleep(3)
            close_button.click()
            # 或者取消弹框
            # alert.accpt()
            time.sleep(2)
            print("close_button process completed.")

        finally:
            # 关闭浏览器
            time.sleep(1)

            driver.quit()

if __name__ == "__main__":
    chrome_driver_path = "D:/chorme/chromedriver-win64/chromedriver.exe"  # 更新为你的实际路径
    url = "http://111.229.67.228:85/login"
    username = "admin"  # 替换为实际的用户名
    password = "123456"  # 替换为实际的密码
    role_value = 'ADMIN'  # 角色值应与页面上的选项文本匹配

    OpenAndLogin.open_and_login(chrome_driver_path, url, username, password, role_value)